package com.epam.cdp.jpa.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.jpa.model.User;
import com.epam.cdp.jpa.utils.SessionAttributes;

public class AuthenticationFilter implements Filter {

    private static final Log log = LogFactory.getLog(AuthenticationFilter.class); 
    
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	HttpServletResponse response = (HttpServletResponse) servletResponse;
	
	String requestURI = request.getRequestURI();
	
	String contextPath = request.getContextPath();
	
	String localPath = requestURI.replaceFirst(contextPath, "");
	
	if (localPath.contains("/secured/")) {
	    User user = (User) request.getSession(true).getAttribute(SessionAttributes.USER.name());
	    if (user == null) {
		response.sendRedirect(contextPath + "/public/login.xhtml");
	    }
	}
	
	filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
	log.info("Custom authentication filter was created");
    }

}
